using UnityEngine;

public class Enemy : MonoBehaviour

{
    public float moveSpeed = 1f;
    public GameObject oldMan;
    public DetectionZone detectionZone;
    public OldMan_i_attack oldManAttack;
    public Rigidbody2D rb;
    private Animator animator;
    private SpriteRenderer sr;
    private bool isFlip = false;

    public float Health {
        set 
        {
            health = value;

            if (health <= 0)
            {
                Defeated();
            }
        }
        get
        {
            return health;
        }
    }

    public float health = 1;

    void FixedUpdate()
    {
        if (detectionZone.detectedObjs.Count > 0)
        {
            Collider2D player = detectionZone.detectedObjs[0];
            if(player)
            {
                Vector2 direction = (player.transform.position - transform.position).normalized;
                rb.AddForce(direction * moveSpeed * Time.deltaTime);

                var heading = player.transform.position - transform.position;
                var distance = heading.magnitude;
                isFlip = heading[0] < 0? true : false;
                sr.flipX = isFlip;
                if (distance < 0.6)
                {
                    animator.SetBool("canAttack", true);
                    // animator.Play("OldMan_attack");
                }
            }
        }
        else 
        {
            animator.SetBool("canAttack", false);
        }
    }

    public void Defeated()
    {
        Instantiate(oldMan, transform.position, transform.rotation);
        Destroy(gameObject);         
    }

    public void TakeDamage(float damage)
    {
        Health -= damage;
    }

    public void OnHit(float damage)
    {
        TakeDamage(damage);
    }

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        sr = GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void StartAttack()
    {
        print(isFlip);
        oldManAttack.StartAttack(isFlip);
    }

    public void StopAttack()
    {
        oldManAttack.StopAttack();
    }
}